﻿using System;
using Birkelund.QueryStrings.Tokens;
using NUnit.Framework;

namespace Birkelund.QueryStrings.Test
{
    public class UriTokenTest
    {
        [Test]
        public void WriteAndRead()
        {
            Uri value = new Uri("http://localhost/test/secure.aspx?id=2");
            UriToken token = new UriToken("returnUrl");
            IUriWriter writer = UriWriter.CreateEmptyFromUri("http://localhost/test/login.aspx");
            writer.SetToken(token, value);

            Assert.AreEqual("http://localhost/test/login.aspx?returnUrl=http%3a%2f%2flocalhost%2ftest%2fsecure.aspx%3fid%3d2", writer.GenerateQueryAsString());
            Assert.AreEqual(value, token.ReadValue(writer.GenerateQueryAsUri()));
        }

        [Test]
        public void Read_InvalidUri()
        {
            UriToken token = new UriToken("returnUrl")
            {
                ExceptionNotificationBehaviour = ExceptionNotificationBehaviour.ThrowException
            };
            IUriWriter writer = UriWriter.CreateFromUri("http://localhost/test/login.aspx?returnUrl=something");

            TokenParserException exception = Assert.Throws<TokenParserException>(() => token.ReadValue(writer.GenerateQueryAsUri()));
            Assert.AreEqual(FailureReason.ParseError, exception.FailureArgs.Reason);
        }

        [Test]
        public void WriteAndRead_WithNull()
        {
            UriToken token = new UriToken("returnUrl")
            {
                RenderIfEmptyValue = true
            };
            IUriWriter writer = UriWriter.CreateEmptyFromUri("http://localhost/test/login.aspx");

            writer.SetToken(token, null);

            Assert.AreEqual("http://localhost/test/login.aspx?returnUrl=", writer.GenerateQueryAsString());
            Assert.IsNull(token.ReadValue(writer.GenerateQueryAsUri()));
        }
    }
}
